import { WeilaCore, WL_ClientType } from 'weilasdk_lite';
import { sendPhoneVerifyCode, getAccountByPhone } from '../../utils/apis';

Page({
  data: {
    logoUrl: 'https://ai-public.mastergo.com/ai/img_res/c828b8063383f6dbf6f26d390029b823.jpg',
    phone: '',
    verificationCode: '',
    canLogin: false
  },

  goBack() {
    wx.navigateBack();
},

  // 更新手机号输入
  onPhoneInput(e: any) {
    const phone = e.detail.value;
    this.setData({ 
      phone,
      canLogin: phone.length === 11 && this.data.verificationCode.length >= 4
    });
  },

  // 更新验证码输入
  onVerificationCodeInput(e: any) {
    const verificationCode = e.detail.value;
    this.setData({ 
      verificationCode,
      canLogin: this.data.phone.length === 11 && verificationCode.length >= 4
    });
  },

  // 获取验证码
  async getVerificationCode() {
    if (this.data.phone.length !== 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    try {
      let rsp = await sendPhoneVerifyCode({
        wx: {
          appid: getApp<IAppOption>().globalData.accountInfo!.miniProgram.appId,
          openid: getApp<IAppOption>().globalData.openId!,
          unionid: getApp<IAppOption>().globalData.unionid!,
          sessionkey: getApp<IAppOption>().globalData.sessionKey!
        },
        phone: this.data.phone,
        countrycode: '86'
      })

          // 获取验证码逻辑
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      });

      console.log('获取到的验证码信息', rsp);
      
    }catch (err) {
      console.error('获取验证码失败', err);
      wx.showToast({
        title: '获取验证码失败',
        icon: 'error'
      });
      return;
    }
  },

  // 登录处理
  async handleLogin() {
    if (!this.data.canLogin) return;

    try {
      let rsp = await getAccountByPhone({
        wx: {
          appid: getApp<IAppOption>().globalData.accountInfo!.miniProgram.appId,
          openid: getApp<IAppOption>().globalData.openId!,
          unionid: getApp<IAppOption>().globalData.unionid!,
          sessionkey: getApp<IAppOption>().globalData.sessionKey!
        },
        phone: this.data.phone,
        verifycode: this.data.verificationCode
      })

      console.log('获取到的账号信息', rsp);
      if (rsp.errcode == 0) {
          let weilaCore: WeilaCore = getApp<IAppOption>().globalData.weilaCore;
          try {
              const ret = await weilaCore.weila_login(rsp.data.account.username, rsp.data.account.passwd, rsp.data.account.countrycode, WL_ClientType.CLIENT_MINIPROGRAM, true);
              console.log("微喇登录结果", ret);
              wx.switchTab({
                  url: '/pages/life/life-main/life-main'
              }).then(() => {
                  console.log("跳转成功");
              }).catch((err) => {
                  console.error("跳转失败", err);
              });
          } catch (err) {
              console.error('微喇登录失败', err);
              wx.showToast({
                  title: '微喇登录失败，请重试:' + err,
                  icon: 'error'
              });
          }
      }else {
          wx.showToast({
              title: "登陆失败:" + rsp.errmsg,
              icon: 'error'
          });
      }
    }catch (err) {
      console.error('登录失败', err);
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
    }
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  }
});
